#include "myfile.hpp"
FILE_ *fopen_(const char *path_name, const char *mode)
{
    int flags = 0;
    int defaultmode = 0666;
    if (strcmp(mode, "r") == 0)
    {
        flags |= O_RDONLY;
    }
    else if (strcmp(mode, "w") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_TRUNC);
    }
    else if (strcmp(mode, "a") == 0)
    {
        flags |= (O_WRONLY | O_CREAT | O_APPEND);
    }
    else
    {
    }
    int fd = 0;
    if (flags & O_RDONLY)
        fd = open(path_name, flags);
    else
        fd = open(path_name, flags, defaultmode);
    if (fd < 0)
    {
        const char *err = strerror(errno);
        write(2, err, strlen(err));
        return NULL;
    }
    FILE_ *fp = (FILE_ *)malloc(sizeof(FILE_));
    assert(fp);
    fp->flags = SYNC_LINE;
    fp->fileno = fd;
    fp->cap = SIZE;
    fp->size = 0;
    memset(fp->buffer, 0, SIZE);
    return fp;
}
void fwrite_(const void *ptr, int num, FILE_ *fp)
{
    memcpy(fp->buffer + fp->size, ptr, num);
    fp->size += num;
    if (fp->flags == SYNC_NOW)
    {
        write(fp->fileno, fp->buffer, fp->size);
        fp->size = 0;
    }
    else if (fp->flags == SYNC_FULL)
    {
        if (fp->cap == fp->size)
        {
            write(fp->fileno, fp->buffer, fp->size);
            fp->size = 0;
        }
    }
    else if (fp->flags == SYNC_LINE)
    {
        if (fp->buffer[fp->size - 1] == '\n')
        {
            write(fp->fileno, fp->buffer, fp->size);
            fp->size = 0;
        }
    }
    else
    {
    }
}
void fflush_(FILE_ *fp)
{
    if (fp->size > 0)
        write(fp->fileno, fp->buffer, fp->size);
    fsync(fp->fileno);
    fp->size = 0;
}
void fclose_(FILE_ *fp)
{
    fflush_(fp);
    close(fp->fileno);
}
int test()
{
    FILE_ *fp = fopen_("./log.txt", "a");
    if (fp == NULL)
    {
        return 1;
    }
    const char *msg = "hello bit\n";
    fwrite_(msg, strlen(msg), fp);
    fclose_(fp);
    return 0;
}
int test1()
{
    FILE_ *fp = fopen_("./log.txt", "w");
    if (fp == NULL)
    {
        return 1;
    }
    int cnt = 10;
    const char *msg = "hello bit \n";
    while (1)
    {
        cnt--;
        fwrite_(msg, strlen(msg), fp);
        sleep(1);
        printf("count:%d\n", cnt);
        if (cnt == 0)
            break;
    }
    fclose_(fp);
}
int main()
{
    // test();
    test1();
    return 0;
}